package com.redis.demo.rabbitmq.rpc;

import com.rabbitmq.client.*;
import com.redis.demo.rabbitmq.Constants.Constants;

import java.io.IOException;
import java.util.SortedSet;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);

        channel.basicQos(1);

        DefaultConsumer consumer=new DefaultConsumer(channel){


            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
                AMQP.BasicProperties basicProperties=new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())

                        .build();
                channel.basicPublish("",Constants.RPC_RESPONSE_QUEUE,basicProperties,body);
                channel.basicAck(envelope.getDeliveryTag(),false);

            }
        };



        //非自动返回
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);

    }
}
